package com.tnovoselec.android.common.async.notif;

import java.util.concurrent.Future;

import android.os.Handler;

import com.tnovoselec.android.common.async.listener.ResultListener;


public class AndroidHandlerNotifier implements Notifier {

	private final Handler handler;

	protected AndroidHandlerNotifier(Handler handler) {
		if (handler == null) {
			throw new NullPointerException("Handler was null!");
		}

		this.handler = handler;
	}

	@Override
	public <K, T> void notify(final ResultListener<K, T> listener, final K key, final Future<T> result) {
		if (listener == null) {
			throw new NullPointerException("Listener is null!");
		} else if (result == null) {
			throw new NullPointerException("Result is null!");
		} else if (!result.isDone()) {
			throw new IllegalStateException("Result has not finished calculating!");
		}

		// Use our handler schedule a runnable on its thread which will perform the notification.
		handler.post(new Runnable() {

			@Override
			public void run() {
				listener.onResult(key, result);
			}
		});
	}
}
